import React, { useEffect, useState, useRef } from "react";
import { Modal, message, Space } from "antd";
import { hiprint } from "vue-plugin-hiprint";
import PrintModal from "./component/PrintModal";
import { getCurrentUser } from "@/utils/authority";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import AssignedReturnClerkModal from "./component/AssignedReturnClerkModal";
import SelectActions from "@/views/components/SelectActions";
import ActionExportExcelModal from "./component/ActionExportExcelModal"; // 导出弹窗
import OrderDetailModal from "./component/OrderDetailModal";
import ReturnSupplier from "./component/ReturnSupplier";
import ExchangeWarehouse from "./component/ExchangeWarehouse";
import useColumns from "./cloumns";
import { getFmcgreturnList, getReturnStatus, getReturnMethods, getRefusalTypes, queryAreaCode } from "./service";
import { hiprintTipsModal } from "@/utils/utils.jsx";
import { useLocation } from "react-router-dom";
import { CloudDownloadOutlined } from '@ant-design/icons';

const FmcmReturns = () => {
	const [visible, setVisible] = useState("");
	const [printParams, setPrintParams] = useState({});
	const [returnClerkParams, setReturnClerkParams] = useState([]);
	const [printType, setPrintType] = useState({});
	const [recordItem, setRecordItem] = useState({}); //每行数据
	const [ApiData, setApiData] = useState({}); //每行数据
	const tableRequest = getFmcgreturnList;
	const areaOption = useRef();
	//退货员列表
	const [takeGoods, setTakeGoods] = useState(null);
	//退货状态
	const [refundStatus, setRefundStatus] = useState([]);

	//退货方式
	const [refundMethod, setRefundMethod] = useState([]);

	//拒退类型
	const [refuseType, setRefuseType] = useState([]);

	const { defaultColumns } = useColumns({ refundStatus, areaOption, refundMethod, refuseType, handleOpenOrderDetailVisible });

	const [columns, setColumns] = useState(defaultColumns);

	const [createTaskData, setCreateTaskData] = useState({});

	const location = useLocation();

	useEffect(() => {
		setColumns(defaultColumns);
	}, [refundStatus, refundMethod, refuseType])

	//获取退货状态枚举
	const queryRefundStatus = async () => {
		const { success, data } = await getReturnStatus();
		if (success) {
			data.map(v => v.label = v.name);
			setRefundStatus(data);
		}
	}
	//获取退货类型枚举
	const queryRefundMethod = async () => {
		const { success, data } = await getReturnMethods();
		if (success) {
			data.map(v => v.label = v.name);
			setRefundMethod(data);
		}
	}
	//获取拒退类型枚举
	const queryRefuseType = async () => {
		const { success, data } = await getRefusalTypes();
		if (success) {
			data.map(v => v.label = v.name);
			setRefuseType(data);
		}
	}

	const handleTakeGoodsChange = value => {
		setTakeGoods(value);
	};

	useEffect(() => {
		queryRefundStatus();
		queryRefundMethod();
		queryRefuseType();
		getQueryAreaCode();
	}, [])

	async function getQueryAreaCode() {
		const { success, data } = await queryAreaCode({ areaCode: "" });
		if (success) {
			areaOption.current = data.map(e => {
				return {
					...e,
					value: e.name,
					label: e.name
				};
			});
		}
	}

	const beforeQuerySearch = ({ API_DATA }) => {
		if (!API_DATA.timeType) {
			API_DATA.timeType = 1;
		}
		const obj = {
			...API_DATA,
			afterSalesOrderNos: API_DATA.afterSalesOrderNos?.split(','),
			logisticsNos: API_DATA.logisticsNos?.split(','),
			outboundNos: API_DATA.outboundNos?.split(','),
			systemNos: API_DATA.systemNos?.split(','),
			uniqueCodes: API_DATA.uniqueCodes?.split(','),
			tradeNos: API_DATA.tradeNos?.split(','),
		}
		setApiData(obj);
		return obj;
	};
	const tableKey = "FmcmPurchase2165";
	const {
		selectedKeys,
		selectedRows,
		fetchList,
		dataSource,
		form,
		query,
		pagination,
		searchSimpleTableProps
	} = useTableConfig({
		tableKey,
		rowKey: "id",
		columns,
		takeGoods,
		tableRequest,
		handleTakeGoodsChange,
		autoFetch: true,
		hasPagination: true,
		hasQuickSearch: true,
		beforeQuerySearch,
		resetSourceData: false,
		hasColsSetting: true,
		hasToggleSearchForm: true,
		columnResize: true
	});

	useEffect(() => {
		if (location.state && location.state?.orderSn) {
			form.resetFields();
			form.setFieldsValue({ uniqueCodes: location.state.orderSn });
			let timer = setTimeout(() => {
				fetchList(form.getFieldsValue());
				clearTimeout(timer);
				timer = null;
			},400)
		}
	}, [location.state?.orderSn])

	const commonHandleClick = (status, record) => {
		if (status == "ProgressModal") {
			setVisible("ProgressModal");
		} else {
			if (selectedRows.length) {
				setVisible(status);
			} else {
				Modal.info({ centered: true, content: "请选择操作数据" });
			}
		}
	};

	//点击指派退货员
	const handleReturnClerk = type => {
		let params = {};
		if (type == 1) {
			if (!selectedRows.length) {
				return message.info("没有可操作的数据，请重新勾选");
			}
			setReturnClerkParams(selectedRows);
			setVisible("AssignedReturnClerkModal");
		}

		if (type == 2) {
			ApiData.pageSize = pagination?.total;
			ApiData.total = 0;
			getFmcgreturnList(ApiData).then(({ success, data }) => {
				if (success) {
					const records = data?.records;
					console.log(records, "records");
					if (!records?.length) {
						message.info("没有可操作的数据，请重新选择");
						return;
					}
					setReturnClerkParams(data?.records);
				}
			});
			setVisible("AssignedReturnClerkModal");
		}
	};

	//点击继续退供
	const handleReturnSupplier = async type => {
		let operaList = [];
		if (type == 1) {
			operaList = selectedRows;
		} else if(type == 2) {
			ApiData.pageSize = pagination?.total;
			ApiData.total = 0;
			START_LOADING();
			const { success, data } = await getFmcgreturnList(ApiData);
			END_LOADING();
			if(success) {
				operaList = data?.records;
			}
		}
		if (!operaList.length > 0) {
			return message.info("没有可操作的数据，请重新勾选或调整筛选条件");
		}
		const list = operaList.filter(v => !['3', '13'].includes(v.returnStatus));
		if (list.length > 0) {
			return Modal.info({
				content: '存在非拒绝退货、商户拒绝状态的唯一码。且当前任务不执行，只允许操作的唯一码全部符合条件时进行执行'
			})
		}
		setReturnClerkParams(operaList);
		setVisible("ReturnSupplier");
	};

	//点击退货转入仓
	const handleExchangeWarehouse = async type => {
		let operaList = [];
		if (type == 1) {
			operaList = selectedRows;
		} else if(type == 2) {
			ApiData.pageSize = pagination?.total;
			ApiData.total = 0;
			START_LOADING();
			const { success, data } = await getFmcgreturnList(ApiData);
			END_LOADING();
			if(success) {
				operaList = data?.records;
			}
		}
		if (!operaList.length > 0) {
			return message.info("没有可操作的数据，请重新勾选或调整筛选条件");
		}
		const list = operaList.filter(v => !['0', '1', '3', '13'].includes(v.returnStatus));
		if (list.length > 0) {
			return Modal.info({
				content: '存在非拒绝退货、商户拒绝、待退货、退货中状态的唯一码。且当前任务不执行，需要勾选唯一码全部满足退供转入仓的条件后进行处理'
			})
		}
		setReturnClerkParams(operaList);
		setVisible("ExchangeWarehouse");
	};

	const handleBatchPrint = type => {
		setPrintType(type);
		if (type == 1) {
			if (!selectedRows.length) {
				return message.info("请选择需要打印的商品");
			}
			setPrintParams(selectedRows);
			setVisible("print");
		}

		if (type == 2) {
			ApiData.pageSize = pagination?.total;
			ApiData.total = 0;
			getFmcgreturnList(ApiData).then(({ success, data }) => {
				if (success) {
					const records = data?.records;
					if (!records?.length) {
						message.info("该页面无商品，无法打印");
						return;
					}
					setPrintParams(records);
					setVisible("print");
				}
			});
		}
	};
	async function handleOpenOrderDetailVisible(record) {
		setVisible("OrderDetailModal");
		setRecordItem(record);
	}
	const CheckFmcmReturnsProps = {
		visible,
		query,
		fetchList,
		recordItem,
		returnClerkParams,
		checkedRows: selectedRows,
		dataSource,
		checkedIds: selectedKeys,
		handleOk() {
			updateTableList(selectedRows);
		},
		handleCancel() {
			setVisible("");
		}
	};
	const PrintModalProps = {
		visible: visible,
		printType,
		dataSource,
		recordItem,
		printParams,
		selectedKeys,
		handleCancel() {
			setVisible("");
			setRecordItem({});
		},
		handleOk(val) {
			setVisible("");
			setRecordItem({});
		}
	};
	const searchData = form.getFieldsValue();
	const realProps = {
		createTaskData,
		onCancel() {
			setVisible("");
		}
	};

	const handleExport = (val) => {
		if (val == 2) {
			//针对筛选项
			const API_DATA = { ...ApiData };
			const obj = {
				businessParam: JSON.stringify({
					...API_DATA,
					uuid: getCurrentUser().uuid,
					current: pagination.current, // 当前页
					size: 9000, // 每页的数量
					businessKey: 2
				}),
				taskType: 4005
			}
			setCreateTaskData(obj);
			setVisible("ProgressModal");
		} else if (val == 3) {
			if (selectedRows.length > 0) {
				const obj = {
					businessParam: JSON.stringify({
						uuid: getCurrentUser().uuid,
						uniqueCodes: selectedRows.map(v => v.uniqueCode),
						businessKey: 3
					}),
					taskType: 4005
				}
				setCreateTaskData(obj);
				setVisible("ProgressModal");
			} else {
				message.info('请选择需要导出的数据');
			}
		}
	}

	const LeftBtns = (
		<Space>
			<SelectActions
				name="指派退货员"
				options={[
					{
						key: "1",
						label: "针对所选项"
					},
					{
						key: "2",
						label: "针对筛选项"
					}
				]}
				onClick={key => {
					handleReturnClerk(key);
				}}
			></SelectActions>
			<SelectActions
				name="继续退供"
				options={[
					{
						key: "1",
						label: "针对所选项"
					},
					{
						key: "2",
						label: "针对筛选项"
					}
				]}
				onClick={key => {
					handleReturnSupplier(key);
				}}
			></SelectActions>
			<SelectActions
				name="打印快销退货码"
				options={[
					{
						key: "1",
						label: "针对所选项"
					},
					{
						key: "2",
						label: "针对筛选项"
					}
				]}
				onClick={key => {
					handleBatchPrint(key);
				}}
			></SelectActions>
			<SelectActions
				name="退供转入仓"
				options={[
					{
						key: "1",
						label: "针对所选项"
					},
					{
						key: "2",
						label: "针对筛选项"
					}
				]}
				onClick={key => {
					handleExchangeWarehouse(key);
				}}
			></SelectActions>
			<SelectActions
				onClick={key => {
					if (key === "导出勾选项") {
						handleExport(3);
					} else {
						handleExport(2);
					}
				}}
				options={[
					{
						label: "导出筛选项"
					},
					{
						label: "导出勾选项"
					}
				]}
			>
				<CloudDownloadOutlined className="main-color" />
				导出
			</SelectActions>
		</Space>
	);
	return (
		<>
			<SearchCheckboxTable key={tableKey} leftBtns={LeftBtns} mounted={false} {...searchSimpleTableProps} />
			{visible == "AssignedReturnClerkModal" && <AssignedReturnClerkModal {...CheckFmcmReturnsProps} />}
			{visible == "print" && <PrintModal {...PrintModalProps} />}
			{visible == "ProgressModal" && <ActionExportExcelModal {...realProps} />}
			{visible == "OrderDetailModal" && <OrderDetailModal {...CheckFmcmReturnsProps} />}
			{visible == "ReturnSupplier" && <ReturnSupplier {...CheckFmcmReturnsProps} />}
			{visible == "ExchangeWarehouse" && <ExchangeWarehouse {...CheckFmcmReturnsProps} />}
		</>
	);
};

export default React.memo(FmcmReturns, () => {
	return true;
});
